package com.hll.listener;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/*
  因为我遇到了下列异常，tomcat关闭后报错，所以参考了网上的解决方法解决了
* com.mysql.jdbc.AbandonedConnectionCleanupThread.run(AbandonedConnectionCleanupThread.java:43)
* */
@WebListener
public class MyContextListener implements ServletContextListener {
  @Override
  public void contextInitialized(ServletContextEvent sce) {}

  // 自己写代码注销驱动
  @Override
  public void contextDestroyed(ServletContextEvent servletContextEvent) {
    // 这里如果Web应用拥有多个数据库的连接，可以一并关闭
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    Driver driver = null;
    while (drivers.hasMoreElements()) {
      try {
        driver = drivers.nextElement();
        DriverManager.deregisterDriver(driver);
      } catch (SQLException ignored) {
      }
    }
    AbandonedConnectionCleanupThread.checkedShutdown();
  }
}
